<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-breadcrumb>
              <a-breadcrumb-item href="">
                <a-icon type="home" />
                <span>首页</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <a-icon type="user" />
                <span>物资信息管理</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <span>
                <template v-if="this.id !== ''"> <a-icon type="edit" />物资信息编辑</template>
                  <template v-else> <a-icon type="folder-add" />物资信息添加</template>
                </span>
              </a-breadcrumb-item>
            </a-breadcrumb>
          </a-col>
          <a-col :span="24">&nbsp;</a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div class="table-page-search-wrapper">
      <a-form :form="form" @submit="handleSubmit">
        <a-row :gutter="24">
          <a-col :span="16">
            <a-form-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-button-group>
                <a-button type="primary" @click="goBack"> <a-icon type="left" />返回 </a-button>
                <a-button type="primary" html-type="submit"> 保存 <a-icon type="right" /></a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
          <a-col :span="8" :style="{ textAlign: 'right' }">
            <a-form-item>
              <a-button-group>
                <a-button type="primary" @click="toAudit">审批 <a-icon type="right" /></a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item style="display: none;width:0px;"  label="id">
              <a-input v-decorator="['id']" />
            </a-form-item>
            <a-form-item label="物资编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['code']" placeholder="请输入物资编码"></a-input>
            </a-form-item>
            <a-form-item label="物资名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name']" :disabled="disabledOne" placeholder="请输入物资名称"></a-input>
            </a-form-item>
            <a-form-item label="物资分类编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['classifyCode']" readOnly @click="onSearchMaterialClassify" placeholder="请输入物资分类编码">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
            <a-form-item label="物资分类名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['classifyName']" placeholder="请输入物资分类名称"></a-input>
            </a-form-item>
            <a-form-item label="库位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['stockPosition']" readOnly @click="onSearchWarehouseStock" placeholder="请输入库位">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['brand']" placeholder="请输入品牌"></a-input>
            </a-form-item>
            <a-form-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['specs']" placeholder="请输入规格"></a-input>
            </a-form-item>
            <a-form-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['model']" placeholder="请输入型号"></a-input>
            </a-form-item>
            <a-form-item label="计量单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['unit']" readOnly @click="onSearchUnit" placeholder="请输入计量单位">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
            <a-form-item label="技术参数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea
                v-decorator="['param']"
                placeholder="请输入技术参数"
                :auto-size="{ minRows: 3, maxRows: 5 }"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="供货商编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['supplierCode']" readOnly @click="onSearchSupplier" placeholder="请输入供货商编号" >
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-item>
            <a-form-item label="供货商名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['supplierName']" :disabled="disabledOne" placeholder="请输入供货商名称"></a-input>
            </a-form-item>
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['status']" :disabled="disabledOne" placeholder="请输入状态"></a-input>
            </a-form-item>
            <a-form-item label="是否需质检" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-checkbox v-decorator="['isQuality']" @change="onChange"></a-checkbox>
            </a-form-item>
            <div class="clearfix">
              <a-upload
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                list-type="picture-card"
                :file-list="fileList"
                @preview="handlePreview"
                @change="handleChange"
              >
                <div v-if="fileList.length < 3">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    上传图片
                  </div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="物资图片预览" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>

    <!-- table区域-begin -->
    <div>
      <a-tabs default-active-key="1">
        <a-tab-pane key="1">
      <span slot="tab">
        <a-icon type="bank" />
        库存信息
      </span>
          <a-table ref="inventoryTable" bordered :data-source="inventoryDataSource" :columns="inventoryColumns">
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2">
      <span slot="tab">
        <a-icon type="shopping" />
        采购记录
      </span>
          <a-table ref="purchaseRecordTable" bordered :data-source="purchaseRecordDataSource" :columns="purchaseRecordColumns">
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
    <supplier-list-modal ref="supplierModal" @ok="onSupplierOk"></supplier-list-modal>
    <material-classify-tree-modal ref="materialClassifyTreeModal"  @ok="materialClassifyOk"></material-classify-tree-modal>
    <warehouse-stock-tree-modal ref="warehouseStockTreeModal"  @ok="warehouseStockOk"></warehouse-stock-tree-modal>
    <mms-material-unit-modal ref="mmsMaterialUnitModal"  @ok="mmsMaterialUnitModalOk"></mms-material-unit-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@lone/lone-vue/src/utils/mixin'
  import { JEditableTableMixin } from '@lone/lone-vue/src/mixins/JEditableTableMixin'
  import { FormTypes } from '@lone/lone-vue/src/utils/JEditableTableUtil'
  import JEditableTable from '@lone/lone-vue/src/components/jeecg/JEditableTable'
  import JDate from '@lone/lone-vue/src/components/jeecg/JDate'
  import { postAction, putAction, deleteAction, getAction } from '@lone/lone-vue/src/api/manage'
  import Vue from 'vue'
  import SupplierListModal from '../base/form/SupplierListModal'
  import MaterialClassifyTreeModal from '../base/form/MaterialClassifyTreeModal'
  import WarehouseStockTreeModal from '../base/form/WarehouseStockTreeModal'
  import MmsMaterialUnitModal from '../base/form/MmsMaterialUnitModal'
  import ACol from 'ant-design-vue/es/grid/Col'

  export default {
    name: 'MmsMaterialInfoDetailsList',
    mixins:[JEditableTableMixin, mixinDevice],
    components: {
      ACol,
      JDate,
      JEditableTable,
      SupplierListModal,
      MaterialClassifyTreeModal,
      MmsMaterialUnitModal,
      WarehouseStockTreeModal
    },
    props:{
      //判断是编辑还是新增
      status:{
        type:String,
        required:false
      },
      //判断是编辑Id
      id:{
        type:String,
        required:false
      },
    },
    watch:{
      status: {
        handler(newVal, oldVal) {
          this.loadFormData()
        },
        immediate: true
      }
    },
    data () {
      return {
        description: 'mms_wz_purchase_quality_details管理页面',
        top: 10,
        dateFormat: 'YYYY-MM-DD HH:mm:ss',
        // 表头
        disabledAll: false,
        disabledOne: false,
        editingKey: '',
        model: {},
        previewVisible: false,
        previewImage: '',
        fileList: [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
          }
        ],
        // 表头
        inventoryColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'仓库',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'库位',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'批次',
            align:"center",
            dataIndex: 'specs'
          },
          {
            title:'入库时间',
            align:"center",
            dataIndex: 'model'
          },
          {
            title:'余量',
            align:"center",
            dataIndex: 'unit'
          },
          {
            title:'可用数量',
            align:"center",
            dataIndex: 'currentArrivalNum'
          }
        ],
        purchaseRecordColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'供货商编码',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'供货商名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specs'
          },
          {
            title:'入库时间',
            align:"center",
            dataIndex: 'model'
          },
          {
            title:'入库数量',
            align:"center",
            dataIndex: 'currentArrivalNum'
          },
          {
            title:'单价',
            align:"center",
            dataIndex: 'price'
          },
          {
            title:'仓库',
            align:"center",
            dataIndex: 'totalPrice'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'totalPrice'
          }
        ],
        formData:{},
        inventoryDataSource: [],
        purchaseRecordDataSource: [],
        url: {
          list: "/base/mmsMaterialInfo/list",
          delete: "/base/mmsMaterialInfo/delete",
          deleteBatch: "/base/mmsMaterialInfo/deleteBatch",
          exportXlsUrl: "/base/mmsMaterialInfo/exportXls",
          importExcelUrl: "/base/mmsMaterialInfo/importExcel",
        },
        dictOptions:{},
      }
    },
    created() {
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      getBase64(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = error => reject(error);
        });
      },
      handleCancel() {
        this.previewVisible = false;
      },
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await this.getBase64(file.originFileObj);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;
      },
      handleChange({ fileList }) {
        this.fileList = fileList;
      },
      onChange(e) {

      },
      loadFormData() {
        let that = this;
        this.inventoryDataSource = [];
        this.purchaseRecordDataSource = [];
        this.form.setFieldsValue({status: '新建'});
        getAction('/base/mmsMaterialCode/getUserInfo', {}).then((res) => {
          if (res.success) {
            let result = res.result;
            if(result){
              let fields = {createBy: result['realname']};
              this.form.setFieldsValue( fields);
            }
          }
        })
        if(this.id !== '@ADD@'){
          let paramsObject = {id: this.id};
          getAction('/base/mmsMaterialInfo/queryById', paramsObject).then((res) => {
            if (res.success) {
              let result = res.result;
              if (result) {
                for(let p in result) {
                  let field = {};
                  field[p] = result[p];
                  this.form.setFieldsValue(field);
                }
                /*let paramsObject = {materialCode: result['code'], warehouseCode:  that['warehouseCode']};
                getAction('/ck/mmsWzWarehouseStock/getStockDetailBatch', paramsObject).then((res) => {
                  if (res.success) {
                    let result = res.result;
                    if (result) {
                      for(let p in result) {
                        let field = {};
                        field[p] = result[p];
                      }
                    }
                  }
                });*/

                /*let paramsObject = {materialCode: result['code'], warehouseCode:  that['warehouseCode']};
               getAction('/ck/mmsWzWarehouseStock/getStockDetailBatch', paramsObject).then((res) => {
                 if (res.success) {
                   let result = res.result;
                   if (result) {
                     for(let p in result) {
                       let field = {};
                       field[p] = result[p];
                     }
                   }
                 }
               });*/

              }
            }
          });
        }
        that.disabledOne = true;
      },
      onSearchSupplier (){
        this.$refs.supplierModal.showSupplierInfo();
      },
      onSupplierOk (selectionRows, num) {
        this.form.setFieldsValue({supplierName: selectionRows.name})
        this.form.setFieldsValue({supplierCode: selectionRows.code})
      },
      onSearchMaterialClassify(){
        this.$refs.materialClassifyTreeModal.showSelectTreeModal('ok');
      },
      materialClassifyOk(selectionRows, num) {
        let classifyName = selectionRows.label;
        classifyName = classifyName.substring(classifyName.indexOf('[') + 1, classifyName.indexOf(']'));
        this.form.setFieldsValue({classifyCode: selectionRows.key, classifyName: classifyName})
      },
      onSearchWarehouseStock(){
        this.$refs.warehouseStockTreeModal.showSelectTreeModal('ok');
      },
      warehouseStockOk(selectionRows, num){
        this.form.setFieldsValue({stockPosition: selectionRows.key})
      },
      onSearchUnit(){
        this.$refs.mmsMaterialUnitModal.showMmsMaterialUnitInfo('ok');
      },
      mmsMaterialUnitModalOk(selectionRows){
        this.form.setFieldsValue({unit: selectionRows.name})
      },
      modalFormOk(record) {
        let that = this;
        if (record && record.id) {
          const newData = [...this.dataSource];
          const target = newData.filter(item => item.id === record.id)[0];
          newData[newData.indexOf(target)] = record;
          this.dataSource = newData;
        }else{
          record['id'] = '';
          this.dataSource.push(record);
        }
      },
      handleDelete: function (id) {
        if(!this.url.delete){
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (that.device == that.LoneDevice_M) {
              that.loadData(1);
            } else {
              that.loadData();
            }

          } else {
            that.$message.warning(res.message);
          }
        });
      },
      handleEdit: function (record, params) {
        this.$refs.modalForm.edit(record, params);
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
      },
      handleAdd: function (params) {
        this.$refs.modalForm.add(params);
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
      },
      toAudit(){
        let that = this, id = that.formData.id;
        putAction('/base/mmsMaterialInfo/audit', {id: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            let result = res.result;
            if (result) {
              that.redirect(id);
            }else {
              that.$message.warning(res.message);
            }
          }
        })
      },
      handleSubmit(e){
        let that = this, paramsObject = {}, id = that.id;
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            for(let param in values){
              this.$set(paramsObject, param, values[param]);
            }
            let action = postAction, url = 'base/mmsMaterialInfo/add';
            if(paramsObject.hasOwnProperty('id') && paramsObject['id']){
              url = 'base/mmsMaterialInfo/edit';
              action = putAction;
            }
            action(url, paramsObject).then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                // this.$emit('ok');
                let result = res.result;
                if (result) {
                  that.redirect(result['id'])
                }
              } else {
                this.$message.warning(res.message);
                that.redirect(id);
              }
            }).finally(() => {
            })
          }
        });
      },
      deleteNow(record){
        let that = this;
        this.dataSource.splice(this.dataSource.indexOf(record),1);
      },
      redirect(id){
        let that = this;
        that.$emit("prevStep");
        that.$emit("nextStep",{id:id,status: ''})
      },
      goBack(){
        this.$emit('prevStep')
      },
      initDictConfig(){
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

</style>